﻿using OTE.Tasks.Commands.Question;
using SharpArch.Domain.Commands;
using SharpArch.NHibernate.Contracts.Repositories;

namespace OTE.Tasks.CommandHandlers.Question
{
    public class QuestionMetaDataDeletedHandler : ICommandHandler<QuestionMetaDataDeletedCommand>
    {
        private readonly INHibernateRepository<Domain.Question> _questionRepository;

        public QuestionMetaDataDeletedHandler(INHibernateRepository<Domain.Question> questionRepository)
        {
            _questionRepository = questionRepository;
        }

        public ICommandResult Handle(QuestionMetaDataDeletedCommand command)
        {
            var uow = _questionRepository.DbContext;

            Domain.Question question = null;

            int i;

            QuestionMetaDataDeletedResult result = null;

            for (i = 0; i < command.Ids.Length; i++)
            {
                question = _questionRepository.Get(command.Ids[i]);
                //check have question or not
                //if already exist then break loop
            }

            if (i == command.Ids.Length)
            {
                for (i = 0; i < command.Ids.Length; i++)
                {
                    question = _questionRepository.Get(command.Ids[i]);
                    _questionRepository.Delete(question);
                }
                result = new QuestionMetaDataDeletedResult(true);
            }
            else
            {
                result = new QuestionMetaDataDeletedResult(false) { Id = command.Ids[i] };
            }

            uow.CommitChanges();

            return result;
        }
    }
}